<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<meta name="viewport" content="width=device-width,initial-scale=1" />
		
		<title></title>
		<script src="../lib/vue.js" type="text/javascript" charset="utf-8"></script>
		<link rel="stylesheet" type="text/css" href="../lib/bootstrap/css/bootstrap.css"/>
	</head>
	<body>
		<div id="app">
			
			<cmtbox @func="loadComments"></cmtbox>
			
			<div class="panel panel-primary">
			  <div class="panel-heading">
			    <h3 class="panel-title">评论列表</h3>
			  </div>
			  
			  <div class="panel-body">
				  <ul class="list-group">
				    <li class="list-group-item"  v-for="item in list" :key="item.id">
				  	  <span class="badge">评论人：{{item.user}}</span>
				  	  {{item.content}}
					  <a href="" @click.prevent="delet(item.id)">删除</a>
				    </li>
				   
				  </ul>
			  </div>
			</div>
		
		</div>
		
		<template id="tmp1">
			<form>
				<div class="form-group">
					<label>评论人：</label>
					<input type="text"  value="" class="form-control" v-model="user"/>
				</div>
				<div class="form-group">
					<label>评论内容：</label>
					<textarea  class="form-control" v-model="content"></textarea>
				</div>
				<div class="form-group">
					<input type="button" value="发表评论" class="btn btn-primary" @click="postComment"/>
				</div>
				
			</form>
		</template>
		<script type="text/javascript">
			
			
			var vm = new Vue({
				el:'#app',
				data:{
					list:[
						{ id:Date.now(), user:'李白',content:'天生我材必有用'},
						{ id:Date.now(), user:'江小白',content:'劝君更尽一杯酒'},
						{ id:Date.now(), user:'小马',content:'我姓马'}
					]
				},
				methods:{
					loadComments(){/* 从本地的localStorage中，加载评论列表 */
						this.list = JSON.parse(localStorage.getItem('cmts') || '[]');
					},
					delet(id){
						var index = this.list.findIndex(item=>{
							if(item.id == id){
								return true;
							}
						})
						this.list.splice(index,1);
						
						localStorage.setItem('cmts',JSON.stringify(this.list));
					}
				},
				created(){
					this.loadComments();
				}
				,
				components:{
					'cmtbox':{
						template:'#tmp1',
						data:function(){
								return{
									user:'',
									content:''
								}
							}
						,
						methods:{
							postComment(){//发表评论方法
								//1、评论数据存放到localStorage  localStorage.setItem
								//2、将评论对象保存到localStorage localStorage只支持存放字符串，要先调用JSON.stringify
								//3、保存最新的评论数据前，先从localStorage获取之前的数据，转换成数组对象（JSON.parse），然后把最新评论
								//push到这个数组
								//4、如果获取到的localStorage为空，则可以返回一个[ ]，让JSON.parse不报错
								var comment = {id:Date.now() ,user:this.user, content:this.content};
								/* 从localStorage中获取所有的评论 */
								var list = JSON.parse(localStorage.getItem('cmts') || '[]');
								list.push(comment);
								/* 重新保存最新的 */
								localStorage.setItem('cmts',JSON.stringify(list));
								
								this.$emit('func'); 
								
								this.user = this.content = '';
							}
						}
					}
				}
			})
		</script>
	</body>
</html>
